import sys
import time

import numpy as np
from PIL import Image
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeWidgetItem

from ui import Ui_MainWindow
import qimage2ndarray


class Window(Ui_MainWindow, QMainWindow):
    sig = pyqtSignal(float, float, float, float, str)
    board_info = pyqtSignal(dict, bool)

    def __init__(self):
        super(Window, self).__init__()
        self.setupUi(self)
        self.image = None
        self.is_det_img = True
        self.is_had_wrong_in_video = False
        self.img_problems = []
        self.found_problems = []
        self.sig.connect(self.add_scroll_item)
        self.board_info.connect(self.set_board_info)
        self.horizontalSlider.valueChanged.connect(self.update_doubleSpinBox)
        self.doubleSpinBox.valueChanged.connect(self.update_horizontalSlider)
        self.btn_choose_image.clicked.connect(self.set_image_file)
        self.btn_change_save_path.clicked.connect(self.set_output_dir)
        self.checkBox_issave.clicked.connect(self.switch_issave)

    def set_board_info(self, info, is_wrong):
        if info:
            self.textEdit_board_msg.setText(("主板正常螺丝： {} 个\n"
                                             "主板松动螺丝： {} 个\n"
                                             "主板缺失螺丝： {} 个\n"
                                             "风扇正常螺丝： {} 个\n"
                                             "风扇松动螺丝： {} 个\n"
                                             "风扇缺失螺丝： {} 个\n"
                                             "风扇完好扇叶： {} 个\n"
                                             "风扇接口松动/未接：{}"
                                             ).format(info['board'], info['board_loose'], info['board_lost'],
                                                      info['fan'], info['fan_loose'], info['fan_lost'],
                                                      info['blade'], "是" if info['plug_base'] > 0 else "否"))
            self.frame_show.setStyleSheet("background-color: rgb(83, 0, 0);" if is_wrong else "background-color: rgb(0, 0, 0);")
            if self.is_det_img:
                self.process_info(info, is_wrong)
            # elif not self.is_had_wrong_in_video:
            #     self.process_info(info, is_wrong)
            #     self.is_had_wrong_in_video = True

        else:
            self.textEdit_board_msg.setText("等待整块主板进入...")

    def process_info(self, info, is_wrong):
        if info['board_loose'] > 0:
            self.add_tree_item("主板螺丝松动", is_wrong)
        if info['board_lost'] > 0:
            self.add_tree_item("主板螺丝缺失", is_wrong)
        if info['fan_loose'] > 0:
            self.add_tree_item("风扇螺丝松动", is_wrong)
        if info['fan_lost'] > 0:
            self.add_tree_item("风扇螺丝缺失", is_wrong)
        if info['plug_base'] > 0:
            self.add_tree_item("风扇接口未接", is_wrong)

    def update_doubleSpinBox(self):
        self.doubleSpinBox.setValue(self.horizontalSlider.value() * .01)

    def update_horizontalSlider(self):
        self.horizontalSlider.setValue(self.doubleSpinBox.value() * 100)

    def switch_issave(self):
        self.line_edit_save_path.setText('')
        self.line_edit_save_path.setEnabled(self.checkBox_issave.isChecked())
        self.btn_change_save_path.setEnabled(self.checkBox_issave.isChecked())

    def set_image_file(self):
        file = QtWidgets.QFileDialog.getOpenFileName(self, "选择待识别的图片", "./",
                                                     "Images (*.png *.jpg);;All Files (*)")
        if file:
            self.lineEdit_image_path.setText(file[0])

    def set_output_dir(self):
        dir = QtWidgets.QFileDialog.getExistingDirectory(self, "选择输出结果目录", "./")
        if dir:
            self.line_edit_save_path.setText(dir)

    def set_frame(self, img):
        self.image = np.array(img)  # 拿到目标帧

    def set_label_img(self, img_np):
        q_image = qimage2ndarray.array2qimage(img_np)
        self.label_img.setPixmap(QPixmap(q_image).scaledToWidth(self.label_img.width()))

    def set_textedit_log(self, log):
        self.textedit_log.textCursor().insertText(
            time.strftime('- %Y-%m-%d %H:%M:%S -\n', time.localtime()) + log + '\n')

    def set_label_fps(self, fps):
        self.label_msg.setText(fps)

    def add_scroll_item(self, xmin, xmax, ymin, ymax, problem):
        if problem in self.found_problems:
            return
        else:
            self.found_problems.append(problem)
            # self.add_tree_item(problem, True)
        frame = QtWidgets.QFrame(self.scrollAreaWidgetContents)
        frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        frame.setFrameShadow(QtWidgets.QFrame.Sunken)
        frame.setMaximumSize(QtCore.QSize(150, 150))
        gridLayout = QtWidgets.QGridLayout(frame)
        label_img = QtWidgets.QLabel(frame)
        label_img.setAlignment(QtCore.Qt.AlignCenter)
        img = self.image[int(ymin):int(ymax), int(xmin):int(xmax)]
        try:
            q_image = qimage2ndarray.array2qimage(img)
        except ValueError:
            return
        label_img.setPixmap(QPixmap(q_image).scaledToWidth(label_img.width()))
        label_problem = QtWidgets.QLabel(frame)
        label_problem.setAlignment(QtCore.Qt.AlignCenter)
        label_problem.setText(problem)
        gridLayout.addWidget(label_img, 0, 0)
        gridLayout.addWidget(label_problem, 1, 0)
        self.horizontalLayout.addWidget(frame)
        self.img_problems.append(frame)

    def clear_scroll(self):
        for widget in self.img_problems:
            widget.deleteLater()
        self.img_problems.clear()

    def add_tree_item(self, msg, is_wrong):
        child = self.tree_widget.topLevelItem(0 if is_wrong else 1)
        node = QTreeWidgetItem(child)
        node.setText(0, msg)  # 第0列，附加消息
        node.setText(1, time.strftime('%H:%M:%S', time.localtime()))
        child.setText(0, ("未" if not is_wrong else '') + "发现问题 ({})".format(child.childCount()))

    def get_config(self):
        config = {
            'device': 'GPU' if self.btn_radio_gpu.isChecked() else 'CPU',
            'save_path': self.line_edit_save_path.text(),
            'threshold': float(self.doubleSpinBox.value()),
            'camera_id': -1,
            'image_file': '',
            'video_file': ''

        }
        suffix = self.lineEdit_image_path.text()[-3:]
        if self.radioButton_camera.isChecked():
            config.update({
                'camera_id': 0
            })
        elif suffix in ['jpg', 'png']:
            config.update({
                'image_file': self.lineEdit_image_path.text()
            })
        elif suffix in ['mp4', 'flv', 'avi']:
            config.update({
                'video_file': self.lineEdit_image_path.text()
            })
        return config


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Window()

    a = w.get_config()

    w.image = np.array(Image.open('test.jpg'))
    # 问题列表
    # for i in range(8):
        # w.add_scroll_item(831, 1020, 505, 564)
        # w.add_scroll_item(831, 900, 300, 564)
        # 树状图
        # w.add_tree_item('hhhhh', '缺螺丝', True)
        # w.add_tree_item('test', '', False)

    # fps
    w.set_label_fps(60)

    # log
    for i in range(20):
        w.set_textedit_log('test')

    w.show()
    sys.exit(app.exec_())
